package handlers

import (
	"encoding/json"

	"ginmt/handlers/requests"
	"ginmt/handlers/response"
	logic2 "ginmt/logic"
	"ginmt/models/dao"
	"ginmt/pkg"

	"github.com/gin-gonic/gin"
)

func Product(appCtx *pkg.AppCtx) func(*gin.Context) {
	return func(ctx *gin.Context) {
		var (
			request requests.ProductRequest
		)
		err := ctx.BindQuery(&request)

		if err != nil {
			response.Failed(ctx, response.FailedCode, err.Error())
			return
		}

		logic := logic2.NewProductLogic(appCtx, ctx, logic2.NewMtRegionalLogic(appCtx, dao.Use(appCtx.Db)))

		data, err := logic.GetProducts(request.ToRequestBody())
		if err != nil {
			response.Failed(ctx, response.FailedCode, err.Error())
			return
		}

		var jsonData map[string]interface{}
		err = json.Unmarshal(data, &jsonData)
		if err != nil {
			response.Failed(ctx, response.FailedCode, err.Error())
			return
		}
		response.Success(ctx, response.SuccessCode, jsonData)
	}
}

func Link(appCtx *pkg.AppCtx) func(*gin.Context) {
	return func(ctx *gin.Context) {
		var (
			request requests.LinkRequest
		)
		err := ctx.BindQuery(&request)
		if err != nil {
			response.Failed(ctx, response.FailedCode, err.Error())
			return
		}

		logic := logic2.NewProductLogic(appCtx, ctx, logic2.NewMtRegionalLogic(appCtx, dao.Use(appCtx.Db)))

		data, err := logic.GetLink(request.ToRequestBody())
		if err != nil {
			response.Failed(ctx, response.FailedCode, err.Error())
			return
		}

		var jsonData map[string]interface{}
		err = json.Unmarshal(data, &jsonData)
		if err != nil {
			response.Failed(ctx, response.FailedCode, err.Error())
			return
		}
		response.Success(ctx, response.SuccessCode, jsonData)
	}
}
